import {Pager} from "./pager.js";
import {UIBase} from "./uibase.js";

export class UIPager extends UIBase{

  constructor((total,itemLimit,arrLimit = 8,triggerRange = 2){
    super();
    this.pager = new Pager(total,itemLimit,arrLimit,triggerRange);
  }

  _bindEvent(element){
    let list = element.querySelectorAll("a");
    list.forEach(a => a.addEventListener("click",e => {
      let page = Number.parseInt(e.target.dataset.page);//______________________
      let old_currentPage = this.pager.currentPage;
      this.pager.go(page);
      if (page !== old_currentPage) {
        this.emit("change",this.pager.result);
      }
      this.render();
    }));
  }

  _render(){
    let {prevGroupPage, arr, nextGroupPage, currentPage, lastPage} = this.pager.result;

    prevGroupPage = prevGroupPage ? `
      <a href = "#" data-page="${prevGroupPage}">${prevGroupPage}</a>\
      <span>...</span>
    `:"";

    arr = arr.map(p => `
      <a href="#" data-page="${p}" class="${p === currentPage ? "active" : ""}">${p}</a>
      `).join("");
      nextGroupPage = nextGroupPage ? `
        <span>...</span>
        <a href="#" data-page="${nextGroupPage}">${nextGroupPage}</a>
      ` : "";

      return `
        <div class="pages">
          <a href="#" data-page="1">首页</a>
          ${prevGroupPage + arr + nextGroupPage}
          <a href="#" data-page="${lastPage}">尾页</a>
        </div>
      `;
  }
}
